package com.google.code.pomhelper;

import java.util.Comparator;

import org.apache.maven.model.Model;
import org.codehaus.plexus.util.StringUtils;

public class Modul {
	private String name;
	private int depth;
	private Model model;
	private String pomPath;

	/**
	 * Constructor.
	 * 
	 * @param depth
	 */
	public Modul(int depth) {
		this.depth = depth;
	}

	/**
	 * Returns the Module name.
	 * 
	 * @param model
	 *            {@link Model}
	 * 
	 * @return Module name
	 */
	private String getModuleName(Model model) {
		String modelName = model.getName();
		String artifactId = model.getArtifactId();

		String groupId = model.getGroupId();

		if (model.getParent() != null && StringUtils.isEmpty(groupId)) {
			groupId = model.getParent().getGroupId();
		}

		StringBuilder sb = new StringBuilder();

		if (StringUtils.isNotEmpty(modelName)) {
			sb.append(modelName);
			sb.append(" (");
			sb.append(concateGroupIdAndArtifactId(groupId, artifactId));
			sb.append(")");
		} else {
			sb.append(concateGroupIdAndArtifactId(groupId, artifactId));
		}

		return sb.toString();
	}

	/**
	 * concates groupdId and artifactId.
	 * 
	 * @param groupId
	 *            the groupId
	 * @param artifactId
	 *            the artifacId
	 * @return groupId:artifactId
	 */
	private String concateGroupIdAndArtifactId(String groupId, String artifactId) {
		return groupId + ":" + artifactId;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Modul [name=");
		builder.append(name);
		builder.append(", depth=");
		builder.append(depth);
		builder.append(", model=");
		builder.append(model);
		builder.append(", pomPath=");
		builder.append(pomPath);
		builder.append("]");
		return builder.toString();
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the depth
	 */
	public int getDepth() {
		return depth;
	}

	/**
	 * @param depth
	 *            the depth to set
	 */
	public void setDepth(int depth) {
		this.depth = depth;
	}

	/**
	 * @return the model
	 */
	public Model getModel() {
		return model;
	}

	/**
	 * @param model
	 *            the model to set
	 */
	public void setModel(Model model) {
		this.model = model;
		setName(getModuleName(model));
	}

	/**
	 * @return the pomPath
	 */
	public String getPomPath() {
		return pomPath;
	}

	/**
	 * @param pomPath
	 *            the pomPath to set
	 */
	public void setPomPath(String pomPath) {
		this.pomPath = pomPath;
	}

	/**
	 * Comparator for Module.
	 * 
	 * @author rm
	 * 
	 */
	public static class ModuleListComparator implements Comparator<Modul> {

		@Override
		public int compare(Modul o1, Modul o2) {
			return o1.getName().compareToIgnoreCase(o2.getName());
		}
	}
}
